import EventEmitter from 'events'
import { TextModel, SelectionModel } from '../models'
export class SourceView extends EventEmitter {
  textModel_
  selectionModel_
  viewContainer_
  constructor(textModel: TextModel, selectionModel: SelectionModel, viewContainer: HTMLElement) {
    super()
    this.textModel_ = textModel
    this.selectionModel_ = selectionModel
    this.viewContainer_ = viewContainer
    this.addEventListener()
  }
  addEventListener() {
    this.textModel_.on('text-change', this.render.bind(this))
  }
  updateDomSelection() {
    const domSelection = window.getSelection()
    if (domSelection) {
      this.emit('selection-change', {
        anchor: domSelection.anchorOffset, focus: domSelection.focusOffset
      })
    }
  }
  domSelectionChangeHandler () {
    const domSelection = window.getSelection()
    console.log(domSelection, 'domSelection')
    if (domSelection) {
        const selectionFromModel = this.selectionModel_.getSelection()
        const anchor = selectionFromModel.anchor
        const range = window.document.createRange()
        console.log(anchor, 'anchor')
        range.setStart(this.viewContainer_.childNodes[0], anchor)
        range.setEnd(this.viewContainer_.childNodes[0], anchor)
        debugger
        domSelection.removeAllRanges()
        domSelection.addRange(range)  
    }
    
}
  render() {
    this.viewContainer_.innerHTML = this.textModel_.getSpacers()
    setTimeout(() => {
      this.domSelectionChangeHandler()
    }, 0);
  }
}